
import React, { useImperativeHandle, useMemo } from 'react';
import { Button, Input } from 'antd';

const Child = React.forwardRef((props, ref) => {
    return (
        <>
            <p>只使用forwardRef</p>
            <Input ref={ref} className='w-40' />

        </>
    )
})
const Child2 = React.forwardRef((props, ref) => {
    const [value, setValue] = React.useState('');
    const clear = () => {
        setValue('');
    }
    // 给父组件暴露clear方法
    useImperativeHandle(ref, () => ({
        clear,
        getValue: () => {
            iptRef.current.blur();
            return value
        }
    }))
    const iptRef = React.useRef(null);
    return (
        <>
            <p>useImperativeHandle方式</p>
            {/* <Input value={value} ref={ref} onChange={e => setValue(e.target.value)} className='w-40' /> */}
            <Input ref={iptRef} value={value} onChange={e => setValue(e.target.value)} className='w-40' />
        </>
    )
})
const ForwardRefPage = () => {
    const childRef = React.useRef(null);
    const child2Ref = React.useRef(null);
   
    return (
        <>
            <div>
                <Child ref={childRef}></Child>
                <Button onClick={() => childRef.current.focus()}>聚焦 </Button>

            </div>
            <div className='mt-10'>
                <Child2 ref={child2Ref}></Child2>
                <Button onClick={() => {
                    child2Ref.current.clear()
                }}>清空 </Button>

                <Button onClick={()=>{console.log(child2Ref.current.getValue())}}>获取并失焦</Button>
            </div>
        </>
    )
};

export default ForwardRefPage;